﻿using System;
using System.Text;
using Castle.DynamicProxy;
using EFI.Service.Configuration;

namespace EFI.Aspects
{
    public class Caching : IInterceptor
    {


        #region IInterceptor Members

        public void Intercept(IInvocation invocation)
        {
            if (!ConfigManager.GetConfigValue<bool>("CachingEnabled",false))
            {
                invocation.Proceed();
                return;
            }

            var cacheProvider = CacheProvider.CacheFactory.GetCache("RequestCacheProvider");

            var sb = new StringBuilder();
            sb.AppendFormat("RC_{0}",
                            invocation.Method.Name);

            for (int i = 0; i < invocation.Arguments.Length; i++)
            {
                if (invocation.Arguments[i] == null)
                    continue;
                sb.AppendFormat("_{0}_{1}", invocation.Method.GetParameters()[i].Name, invocation.Arguments[i].GetHashCode());
            }

            string key = sb.ToString();

            object result = cacheProvider.Get(key);
            if (result != null)
            {
                invocation.ReturnValue = result;
            
                return;
            }
            try
            {
                invocation.Proceed();
                if (((PrimitiveResponse)invocation.ReturnValue).ResponseCode == CommonTypes.ResponseCodes.Successful 
                    || ((PrimitiveResponse)invocation.ReturnValue).ResponseCode == CommonTypes.ResponseCodes.NoRecordFound)
                    cacheProvider.Add(key, invocation.ReturnValue, DateTime.UtcNow);

            }
            catch
            {
            }
        }

        #endregion


    }
}
